<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 查找班级 -->
            <el-input
              placeholder="请输入查找内容"
              v-model="queryInfo.query"
              class="input-with-select"
              clearable
              @clear="clearInput"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchDept"
              >
              </el-button>
            </el-input>
        </el-col>
        <!-- 添加院系模块 -->
            <el-col :span="16">
              <div class="right">
                <el-button type="success" plain @click="excelShow">
                  导出Excel表格
                </el-button>
                <el-button type="success" plain @click="excelImport">
                  批量导入
                </el-button>
                <el-button type="primary" @click="addDept">
                  添加院系
                </el-button>
              </div>
            <!-- 批量导入数据 -->
            <el-dialog title="导入文件" :visible.sync= "excelImportShow">
                <el-upload class="upload-demo" :limit="1" :file-list="fileList" :before-upload="beforeUpload">
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
                    <a href="/financial-admin/exportInOutBusiClass-excel" rel="external nofollow" download="模版">
                    <el-button size="small" type="success">下载模板</el-button></a>
                    <div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
                </el-upload>
                <div slot="footer" class="dialog-footer">
                    <el-button @click.native="excelImportShow = false">取消</el-button>
                    <el-button type="primary" @click.native="submitUpload()" :loading="addLoading">提交</el-button>
                </div>
            </el-dialog>
            <el-dialog
              title="添加院系"
              :visible.sync=  "dialogVisible"
              width="50%">
              <el-form :label-position="labelPosition" label-width="80px" :model="departmentForm">
                <el-form-item label="院系名称:" prop="name">
                  <el-input v-model="departmentForm.name" placeholder="请输入院系名" ></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">              
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirm()">确 定</el-button>
              </span>
            </el-dialog>
          </el-col>
        </el-row>
        <!-- 展示所有企业 -->
            <el-table
            :data="department"
            style="width: 100%; top: 20px">
              <el-table-column
                fixed
                prop="id"
                label="编号"
                >
              </el-table-column>
              <el-table-column
                prop="name"
                label="院系名"
                >
              </el-table-column>
              <el-table-column prop="univInfo.schoolName" label="所属高校"></el-table-column>
              <el-table-column
                prop="createTime"
                label="创建时间"
                >
              </el-table-column>
              <el-table-column
                prop="modiTime"
                label="编辑时间"
                >
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                >
                <template slot-scope="scope">
                  <el-button @click="handleClick(scope.row.id)" type="text" icon="el-icon-setting" size="mini">班级管理</el-button>
                  <el-button @click="edit(scope.row)" type="text" icon="el-icon-edit" size="small">编辑</el-button>
                  <el-button @click="deleteDeptById(scope.row.id)" type="text" style="color: #fa6962" icon="el-icon-delete" size="small">删除</el-button>
                </template>
              </el-table-column>      
            </el-table>
      <!-- 分页 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum"
      :page-sizes="[5, 10, 15]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import {
  getDepartment,
  searchDeptByName,
  addDept,
  updateDept,
  deleteDept,
  exportExcel
} from "#/OrganizationManagement/department.js";
import { addLogs } from "#/Home/Home.js";

export default {
  name: "Department",
  meta: {
    title: "院系管理",
  },
  data() {
    return {
      queryInfo: {
        //查询的内容
        query: "",
        // 当前页数
        pageNum: 1,
        // 每页显示多少数据
        pageSize: 5,
      },
      department: [],
      select: "",
      //总数据条数
      total: 0,
      //添加企业弹窗
      dialogVisible: false,
      updateFlag: false,
      labelPosition: "right",
      departmentForm: {},
      excelImportShow: false,
      id: "",
      fileList: [],
      fileName: "",
      addLoading: false,
      value: "",
    };
  },
  created() {
    this.id = this.$route.query.id;
    this.getDepartments();
  },
  methods: {
    // 所有机构（院系）信息
    async getDepartments() {
      await getDepartment(
        this.id,
        this.queryInfo.pageNum,
        this.queryInfo.pageSize
      ).then((res) => {
        const result = res.data;
        console.log(result);
        if (result.ret === 0) {
          this.department = result.orgs.depts.content;
          this.total = result.orgs.depts.totalElements;
        } else {
          this.$message.error("服务器请求错误！");
        }
      });
    },
    confirm() {
      if (this.addFlag) {
        console.log(this.departmentForm);
        this.departmentForm.univId = this.$route.query.id;
        addDept(this.departmentForm).then((res) => {
          if (res.data.ret == 0) {
            console.log(res.data.orgs);
            this.$message.success("添加成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "添加了新的院系信息",
            });
          }
          this.getDepartments();
        });
      } else {
        updateDept(this.departmentForm.id, this.departmentForm).then((res) => {
          if (res.data.ret == 0) {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "修改了院系信息",
            });
          }
          this.getDepartments();
        });
      }
    },
    clearInput() {
      this.queryInfo.pageNum = 1;
      this.queryInfo.pageSize = 5;
      this.getDepartments();
    },
    addDept() {
      this.addFlag = true;
      this.departmentForm = {
        name: "",
      };
      // console.log(departmentForm.univId)
      this.dialogVisible = true;
    },
    edit(obj) {
      this.addFlag = false;
      Object.assign(this.departmentForm, obj);
      this.dialogVisible = true;
    },
    //通过企业名模糊搜索院系
    async searchDept() {
      if (!this.queryInfo.query) {
        return this.$message.error("请输入名称");
      }
      this.queryInfo.pageNum = 1;
      await searchDeptByName(this.queryInfo, this.id).then((res) => {
        if (res.status === 200) {
          console.log(res.data.orgs);
          this.department = res.data.orgs.dept.content;
          this.total = res.data.orgs.dept.totalElements;
          if (this.department === []) {
            this.$message.info("搜索结果为空");
          } else {
            this.$message.success("搜索成功！");
          }
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    deleteDeptById(id) {
      this.$confirm(
        "此操作将永久删除该院系, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(confirmResult => {
        if(confirmResult === 'confirm') {
          deleteDept(id).then((res) => {
            if (res.data.ret == 0) {
              this.$message.success("删除成功！");
              addLogs({
                userId: window.sessionStorage.getItem("userId"),
                behavior: "成功删除了院系信息",
              });
            }
            this.getDepartments();
          });
        }
      }).catch((err) => err);
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getDepartments();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getDepartments();
    },
    handleClick(id) {
      this.$router.push({
        path: `/OrganizationManagement/Class`,
        query: {
          id
        }
      });
    },
    // 导出Excel表格
    async excelShow() {
      await exportExcel().then(res => {
        if(res.status === 200) {
          const blob = new Blob([res.data], {  // res 为后台返回数据
            type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
          });
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = `院系信息.xlsx`;
            elink.style.display = 'none';
            elink.target = '_blank';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
        }
      })
    },
    excelImport() {},
    beforeUpload() {},
  },
};
</script>
<style scoped>
.right {
  float: right;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>

